package com.enqualcomm.kids.component.command;



import android.os.SystemClock;

import com.android.volley.socket.ServerAddress;
import com.android.volley.socket.SocketStack;
import com.enqualcomm.kids.component.HeartService;
import com.enqualcomm.kids.component.MyApplication;

import java.net.Socket;

import common.utils.MyLogger;
import common.utils.NetUtil;

/**
 * Created by yinzhiqun on 2015/10/27.
 *
 */
public class HeartCommand implements BaseCommand {
    private String params;
    private ServerAddress serverAddress;

    public HeartCommand(ServerAddress serverAddress, String userid, String userkey){
        this.serverAddress = serverAddress;
        params = "{\"cmd\":\"heartbeat\",\"userid\":\""+userid+"\",\"userkey\":\""+userkey+"\"}";
    }

    @Override
    public int execute() {
//        MyLogger.jLog().i("execute()");
        MyApplication context = MyApplication.getInstance();
        if (context!=null&&context.isRunningForeground()) {

            if (NetUtil.checkNet(context)) {
                try {
                    Socket socket = SocketStack.initSocket(serverAddress);
                    SocketStack.send(socket, params.getBytes());
                    byte[] bytes = SocketStack.receive(socket);
                    SocketStack.closeSocket(socket);

                    String result = new String(bytes);
                    MyLogger.jLog().i(params);
                    MyLogger.jLog().i(result);
                    if ("{\"code\":0,\"desc\":\"\",\"result\":\"OK\"}".equals(result)){
                        //发送成功

                        HeartService.lastSendHeartCommandTime = SystemClock.elapsedRealtime();//记录发送时的时间
                        return STATUS_OK;//发送成功，不需要重新发送
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                return ERROR;//io异常或者服务器返回code不为0
            }else{
                return NO_CONNECTION;//没有网络连接，尝试重新发送
            }

        }else{
            return STATUS_OK;//在后台，不需要重新发送
        }

    }
}
